package com.traffic.between.util;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

@SuppressWarnings("deprecation")
public class HttpUtil {
	public static String sendData(String url, String data) {
		CloseableHttpClient httpclient = HttpClients.createDefault();

		HttpPost post = new HttpPost(url);
		StringEntity strEntity = new StringEntity(data, ContentType.APPLICATION_JSON);
		post.setEntity(strEntity);

		String responseContent = null;
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				responseContent = EntityUtils.toString(entity, "UTF-8");
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
			responseContent = "{\"code\": \"11111\",\"msg\":\"" + e.getMessage() + "\"}";
		} catch (IOException ex) {
			ex.printStackTrace();
			responseContent = "{\"code\": \"11111\",\"msg\":\"" + ex.getMessage() + "\"}";
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					if (httpclient != null) {
						try {
							httpclient.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return responseContent;
	}

	public static String sendData2(String url, String json) {
		String resultStr = "";
		@SuppressWarnings({ "resource" })
		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost(url);
		try {
			if (null != json) {
				StringEntity entity = new StringEntity(json.toString(), "UTF-8");
				entity.setContentEncoding("UTF-8");
				entity.setContentType("application/json");
				method.setEntity(entity);
				method.setHeader("Connection", "close");
			}
			HttpResponse result = httpClient.execute(method);

			if (result.getStatusLine().getStatusCode() == 200)
				try {
					resultStr = EntityUtils.toString(result.getEntity(), "UTF-8");
				} catch (Exception e) {
					e.printStackTrace();
				}
			else
				resultStr = "{\"code\": \"11111\",\"msg\":\"订购时发生异常,请稍后再试.\",\"data\":{}}";
		} catch (IOException e) {
			e.printStackTrace();
			resultStr = "{\"code\": \"11111\",\"msg\":\"" + e.getMessage() + "\"}";
		} finally {
			if (method != null) {
				method.releaseConnection();
				method = null;
			}
		}
		return resultStr;
	}
}